import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author long.hua
 * @version 1.0.0
 * @since 2017-02-05 23:41
 */
public class Log {

    private static BufferedWriter bw = null;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static {
        try {
            bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("move.log", true)));
        } catch (IOException e) {
            System.out.println("创建文件失败");
            e.printStackTrace();
        }
    }


    public static void info(String msg) {
        info(msg, null);
    }

    public static void info(String msg, Throwable t) {
        try {
            msg = composeMsg(msg);
            bw.write(msg);
            System.out.print(msg);

            if (t != null) {
                for (StackTraceElement element : t.getStackTrace()) {
                    msg = sdf.format(new Date()) + " " + element.toString() + System.lineSeparator();
                    bw.write(msg);
                    System.out.print(msg);
                }
            }

            bw.flush();

        } catch (IOException e) {
            System.out.println("写入日志失败");
            e.printStackTrace();
        }
    }

    private static String composeMsg(String msg){
        if(msg.startsWith("\n")){
            msg = sdf.format(new Date()) + " " + msg.replaceFirst("\n", "") + System.lineSeparator();
        } else {
            msg = sdf.format(new Date()) + " " + msg + System.lineSeparator();
        }
        return msg;
    }

    public static void close() {
        try {
            System.out.println("关闭日志输出");
        } finally {
            try {
                bw.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
